package com.adu.music.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @author duchuanchuan
 * @date 2016/12/7
 */
public class CommonUtils {
    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    /**
     * 如果str是空，返回0
     * @param str 字符串
     * @return 数字结果
     */
    public static int parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            logger.error("字符串转换异常:{}", str);
            return 0;
        }
    }

    public static String formatMap2Json(List<Map<String, Object>> list) {
        JSONArray array = new JSONArray();
        list.forEach(map -> {
            JSONObject jsonObj = new JSONObject();
            for (Map.Entry entry : map.entrySet()) {
                jsonObj.put(entry.getKey().toString(), entry.getValue());
            }
            array.add(jsonObj);
        });
        return array.toJSONString();
    }

    /**
     * 根据响应速度判定优先级
     * @param speed 响应速度，单位秒
     * @return 代理优先级，共分1-5级，1级最高, -1表示不可用
     */
    public static int judgePorxyPriority(double speed) {
        int priority = -1;
        if (speed <= 1) {
            priority = 1;
        } else if (speed <= 3) {
            priority = 2;
        } else if (speed <= 4) {
            priority = 3;
        } else if (speed <= 5) {
            priority = 4;
        } else if (speed <= 7) {
            priority = 5;
        }
        return priority;
    }
}
